<template>
  <div>
    <el-card shadow="always">
      <el-form :inline="true" :model="formInline">
        <el-form-item label="菜单名 :" class="el-form-item-custom">
          <el-input v-model="formInline.name" placeholder="菜单名" size="small"></el-input>
        </el-form-item>
        <el-form-item class="el-form-item-custom">
          <el-button type="text" @click="handleClick(formInline,'search')" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <hyl-table :tableData="tableData" :columns="columns" :specialColumns="specialColumns" v-on:tableSelection="tableSelection">
      <template slot="buttons">
        <el-button type="text" icon="el-icon-edit" @click="handleClick({},'edit')">编辑</el-button>
        <el-button type="text" icon="el-icon-circle-plus-outline" @click="handleClick({},'add')">添加</el-button>
        <el-button type="text" icon="el-icon-delete" @click="handleClick({},'delete')">删除</el-button>
        <el-button type="text" icon="el-icon-warning" @click="handleClick({},'levelSelect')">调整层级</el-button>
      </template>
      <!-- 定制表格单元格所显示内容 -->
      <div slot="type" slot-scope="scope">{{scope.$row.type ===1 ? '菜单' : '权限'}}</div>
    </hyl-table>
    <hyl-pagination :total="total" v-on:fetch="fetch" :page-sizes="[5,10,15]"/>

    <el-dialog title="层级选择(定制)" :visible="levelSelectVisble" width="40%">
      <el-form>
        <el-form-item label="层级选择">
          <el-input v-model="pid" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <el-tree
        :data="levelSelectData"
        node-key="id"
        :check-strictly="true"
        :show-checkbox="true"
        :accordion="true"
        ref="levelSelect"></el-tree>
      <span slot="footer">
        <el-button type="text" @click="handleOk({},'selected')"><i class="fa fa-check fa-fw">&nbsp;</i>选择层级</el-button>
        <el-button type="text" @click="handleCancel('levelSelect')"><i class="fa fa-remove fa-fw">&nbsp;</i>取 消</el-button>
        <el-button type="text" @click="handleOk({},'levelSelect')"><i class="fa fa-plus fa-fw">&nbsp;</i>确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="40%">
      <el-form  label-width="80px" :model="rowData">
        <el-form-item label="菜单名">
          <el-input v-model="rowData.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel('edit')"><i class="fa fa-remove fa-fw">&nbsp;</i>取 消</el-button>
        <el-button type="primary" @click="handleOk(rowData,'edit')"><i class="fa fa-plus fa-fw">&nbsp;</i>确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加"  :visible="addDialogVisible" width="40%" :show-close="false">
      <el-form ref="addForm" label-width="80px" status-icon :model="addData" :rules="addDataRule" size="small">
        <el-form-item label="菜单名" prop="name">
          <el-input type="text" v-model="addData.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="路径" prop="url">
          <el-input v-model="addData.url"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="addData.type">
            <el-option label="菜单" value="1"></el-option>
            <el-option label="权限" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="text" @click="handleCancel('add')"><i class="fa fa-remove fa-fw">&nbsp;</i>取 消</el-button>
        <el-button type="text" @click="handleOk(addData,'add')"><i class="fa fa-plus fa-fw">&nbsp;</i>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import hylTable from '@/components/table'
import hylPagination from '@/components/pagination'
import {fetch, del, put, post} from '@/utils/http'
export default {
  name: 'Menu',
  components: {
    hylTable,
    hylPagination
  },
  mounted: function () {
    this.fetch()
  },
  data () {
    let validateName = (rule, value, callback) => {
      // 只能存在中文与字母
      let pattern = /[\u4e00-\u9fa5A-Za-z]{2,16}/
      if (pattern.test(value)) {
        fetch('long-base-upms/sysMenu/getByName', {name: value}).then((res) => {
          if (res.data && res.data.id) {
            callback(new Error('该名称已存在!'))
          } else {
            console.log('名称测试OK')
            callback()
          }
        })
      } else {
        callback(new Error('请输入字母中文!'))
      }
    }
    let validateUrl = (rule, value, callback) => {
      let pattern = /^[/][a-z/0-9]{3,29}/
      if (value) {
        if (pattern.test(value)) {
          callback()
        } else {
          callback(new Error('请输入4-30个小写字母,/与数字,或直接为空'))
        }
      } else {
        callback()
      }
    }
    return {
      tableData: [],
      total: 0,
      page: 1,
      limit: 5,
      specialColumns: [{
        type: 'selection',
        width: '55'
      }, {
        type: 'index',
        indexMethod: this.indexMethod
      }],
      columns: [{
        prop: 'name',
        label: '名称',
        width: '180'
      }, {
        prop: 'url',
        label: '路径',
        width: '160'
      }, {
        prop: 'type',
        label: '类型',
        width: '55'
      }, {
        prop: 'level',
        label: '层级',
        width: '120'
      }, {
        fixed: '',
        prop: 'seq',
        label: '序例',
        width: '240'
      }],
      formInline: {
        name: '',
        region: '',
        createDateTimeStart: '',
        createDatetimeEnd: ''
      },
      editDialogVisible: false,
      addDialogVisible: false,
      grantDialogVisible: false,
      levelSelectVisble: false,
      multipleSelection: [],
      rowData: {},
      addData: {
        name: '',
        type: 0,
        url: '',
        pid: null
      },
      addDataRule: {
        name: [
          {validator: validateName, trigger: 'blur'}
        ],
        url: [{
          validator: validateUrl, trigger: 'blur'
        }]
      },
      filterText: '',
      treeData: [],
      pid: '',
      levelSelectData: []
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    getCheckedKeys () {
      console.log(this.$refs.tree.getCheckedKeys())
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    tableSelection (val) {
      this.multipleSelection = val
    },
    handleClick (row = {}, type = '') {
      switch (type) {
        case 'add':
          this.addDialogVisible = true
          for (let item in this.addData) {
            this.addData[item] = ''
          }
          // this.$refs['addData'].resetFields()
          break
        case 'delete':
          if (this.multipleSelection.length > 0) {
            let ids = ''
            let names = ''
            this.multipleSelection.forEach((selection) => {
              ids = ids + selection.id + ','
              names = names + selection.name + ','
            })
            this.$confirm(names + '确定要删除, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              del('long-base-upms/sysMenu/deleteBatch', {params: {ids: ids.slice(0, ids.length - 1)}}).then((res) => {
                this.$message.success('删除成功!')
                this.fetch()
              })
            })
          } else {
            this.$confirm('此操作需要至少选中一行, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
          }
          break
        case 'edit':
          if (this.multipleSelection.length === 1) {
            this.rowData = this.multipleSelection[0]
            this.editDialogVisible = true
          } else {
            this.$confirm('此操作只能选中一行, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
          }
          break
        case 'search':
          let page = {
            page: 1,
            limit: 5
          }
          Object.assign(page, row)
          this.fetch(page)
          // 对formLine作清空操作
          for (let item in this.formInline) {
            this.formInline[item] = ''
          }
          break
        case 'levelSelect':
          if (this.multipleSelection && this.multipleSelection.length === 1) {
            this.levelSelectVisble = true
            fetch('long-base-upms/sysMenu/getAllTreeNode').then((res) => {
              if (res.status === 200) {
                this.levelSelectData = res.data.treeNodeList
              } else {
                this.$message(res.message)
              }
            })
          } else {
            this.$message('只能选择一行!')
          }
          break
        default:
          alert('其它操作')
      }
    },
    handleOk (row, type) {
      switch (type) {
        case 'edit':
          put('long-base-upms/sysMenu/update', row).then((res) => {
            const h = this.$createElement
            this.$message({
              message: h('p', null, [
                h('i', { style: 'color: teal' }, '更新成功!')
              ])
            })
            this.editDialogVisible = false
          })
          break
        case 'add':
          this.$refs['addForm'].validate((valid) => {
            console.log(valid)
            if (valid) {
              post('long-base-upms/sysMenu/add', row).then((res) => {
                this.$message.success('添加成功!')
                this.addDialogVisible = false
                this.$refs['addForm'].resetFields()
                this.fetch()
              })
            }
          })
          break
        case 'levelSelect':
          if (this.pid) {
            put('long-base-upms/sysMenu/update', {
              id: this.multipleSelection[0].id,
              pid: this.pid
            }).then((res) => {
              if (res.status === 200) {
                this.levelSelectVisble = false
                this.pid = ''
              }
              this.$message(res.message)
            })
          } else {
            this.$message('请先选择层级!')
          }

          break
        case 'selected':
          // this.$refs.levelSelect.getCheckedKeys()
          let keys = this.$refs.levelSelect.getCheckedKeys()
          if (keys && keys.length === 1) {
            this.pid = keys[0]
          } else {
            this.$message('只能选择一个层级!')
          }
          break
        default:
          alert('其它操作!')
          break
      }
    },
    handleCancel (type) {
      switch (type) {
        case 'edit':
          this.editDialogVisible = false
          break
        case 'add':
          this.addDialogVisible = false
          break
        case 'levelSelect':
          this.levelSelectVisble = false
          this.pid = ''
          break
        default:
          break
      }
    },
    fetch (page = {
      page: 1,
      limit: 5
    }) {
      fetch('long-base-upms/sysMenu/page', page).then((res) => {
        this.tableData = res.data.rows
        this.total = res.data.total
        this.page = page.page
        this.limit = page.limit
      })
    }
  }
}
</script>

<style scoped>
</style>
